﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using VINETLIFE.BL;
using System.Web.UI.WebControls;
using VINETLIFE.DO;
using VINETLIFE.Data;
using System.Data;
using VINETLIFE.BaseClass;

namespace VINETLIFE.AdminCP
{
    public partial class ListOrders : System.Web.UI.Page
    {
        cmsOrdersDO objOrder = new cmsOrdersDO();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ddlPaymentMethodDataSource();
                grvOrdersDataSource();
                ddlCustomerDataSource();
                ddlSystemStatusDataSource();
                ddlTransactionStatusDataSource();
            }
        }
        protected void ddlTransactionStatusDataSource()
        {
            ddlTransactionStatus.DataSource = new cmsTransactionStatusBL().SelectAll();
            ddlTransactionStatus.DataBind();
        }
        protected void grvOrdersDataSource()
        {
            int customerId = int.Parse(ddlCustomer.SelectedValue);
            string paymentMethod = ddlPaymentMethod.SelectedValue;
            string accountCode = "";
            string orderBy = ddlSort.SelectedValue.Equals("1") ? "Id desc" : "Id asc";
            string systemStatus = ddlSystemStatus.SelectedValue;
            string orderTransactionStatus = ddlTransactionStatus.SelectedValue;
            string statusNotIn = "";
            if (ddlSystemStatus.SelectedValue.Equals("ORDER_H") || ddlSystemStatus.SelectedValue.Equals("ORDER_D"))
            {
                statusNotIn = "SystemStatus NOT IN ('ORDER_X')";
            }
            else
            {
                statusNotIn = "SystemStatus NOT IN ('ORDER_H','ORDER_D')";
            }

            grvOrders.DataSource = new DataView(new cmsOrdersBL().SearchAdvance(customerId, paymentMethod, accountCode, orderBy, systemStatus, orderTransactionStatus, statusNotIn), statusNotIn, "", DataViewRowState.CurrentRows).ToTable();
            grvOrders.DataBind();
        }
        protected void ddlCustomerDataSource()
        {
            ddlCustomer.DataSource = new cmsCustomerBL().GetByIsVangLai(false);
            ddlCustomer.DataBind();
        }
        protected void grvOrders_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            DataRowView drview = e.Row.DataItem as DataRowView;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                int orderId = int.Parse(drview["Id"].ToString());
                int customerId = int.Parse(drview["CustomerId"].ToString());

                Repeater rptCustomers = (Repeater)e.Row.FindControl("rptCustomers");
                if (rptCustomers != null)
                {
                    List<cmsCustomerDO> lstCustomer = new List<cmsCustomerDO>();
                    lstCustomer.Add(new cmsCustomerBL().Select(new cmsCustomerDO { Id = customerId }));
                    rptCustomers.DataSource = lstCustomer;
                    rptCustomers.DataBind();
                }

                string orderTransactionStatus = EnumTransactionOrderStatus.V_ORDER_NEW;
                string invoiceNumber = "";
                string orderStatus = EnumSystemStatus.V_ORDER_ACTIVE;
                try
                {
                    orderTransactionStatus = drview["TransactionOrderStatus"].ToString();
                }
                catch { orderTransactionStatus = EnumTransactionOrderStatus.V_ORDER_NEW; }
                try
                {
                    invoiceNumber = drview["InvoiceNumber"].ToString();
                }
                catch
                {

                    invoiceNumber = "";
                }
                try
                {
                    orderStatus = drview["SystemStatus"].ToString();
                }
                catch
                {

                    orderStatus = "";
                }
                Button btnHide = (Button)e.Row.FindControl("btnHide");
                Button btnDeleteOrder = (Button)e.Row.FindControl("btnDeleteOrder");
                Button btnDetail = (Button)e.Row.FindControl("btnDetail");
                Button btnCancelOrder = (Button)e.Row.FindControl("btnCancelOrder");
                Button btnFinish = (Button)e.Row.FindControl("btnFinish");

                if (orderTransactionStatus.Equals(EnumTransactionOrderStatus.V_ORDER_COMPLETED))
                {
                    DisableButton(btnFinish, invoiceNumber);
                    DisableButton(btnCancelOrder, invoiceNumber);
                }
                else if (orderTransactionStatus.Equals(EnumTransactionOrderStatus.V_ORDER_CANCEL))
                {
                    DisableButton(btnFinish, invoiceNumber);
                    DisableButton(btnCancelOrder, invoiceNumber);
                }
                if (orderStatus.Equals(EnumSystemStatus.V_ORDER_HIDDEN))
                {
                    DisableButton(btnFinish, invoiceNumber);
                    DisableButton(btnCancelOrder, invoiceNumber);
                    DisableButton(btnHide, invoiceNumber);
                }
                else if (orderStatus.Equals(EnumSystemStatus.V_ORDER_DELETE))
                {
                    DisableButton(btnFinish, invoiceNumber);
                    DisableButton(btnCancelOrder, invoiceNumber);
                    DisableButton(btnHide, invoiceNumber);
                    DisableButton(btnDeleteOrder, invoiceNumber);
                }
            }
        }
        public void DisableButton(Button btn, string invoiceNumber)
        {
            btn.Enabled = false;
            btn.Attributes.Add("onclick", Alert(invoiceNumber));
            btn.CssClass = "disable-button button-gg-green";

        }
        public string Alert(string invoiceNumber)
        {
            return "alert('Không thể thực hiện chức năng này cho đơn hàng: " + invoiceNumber + "')";
        }
        public string ReturnItems(object e)
        {
            string returnItem = "";
            if (e == null)
            {
                returnItem = "";
            }
            else
            {
                int orderId = int.Parse(e.ToString());
                DataTable dtDetail = new cmsOrderDetailsBL().GetByOrderId(orderId);
                if (dtDetail.Rows.Count > 0)
                {
                    for (int i = 0; i < dtDetail.Rows.Count; i++)
                    {
                        returnItem += dtDetail.Rows[i]["ProductTitle"] + ", ";
                    }
                }
            }
            return returnItem;
        }
        cmsOrdersBL ItemBL = new cmsOrdersBL();
        protected void dropIsEnable_SelectedIndexChanged(object sender, EventArgs e)
        {
        }
        protected void dropCountRow_SelectedIndexChanged(object sender, EventArgs e)
        {
            lbThongBao.Text = "";
            grvOrders.PageSize = Convert.ToInt32(dropPageSize.SelectedValue);
            grvOrdersDataSource();
        }
        protected void ddlPaymentMethodDataSource()
        {
            ddlPaymentMethod.DataSource = new cmsPaymentMethodBL().SelectAll();
            ddlPaymentMethod.DataBind();
        }
        protected void ddlSystemStatusDataSource()
        {
            ddlSystemStatus.DataSource = new cmsSytemStatusBL().SelectByType("ORDER");
            ddlSystemStatus.DataBind();
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            grvOrders.DataSource = new cmsOrdersBL().GetByOrderCode(txtMaHoaDon.Text.Trim());
            grvOrders.DataBind();
            UpdatePanel1.Update();
        }

        protected void btnShowAll_Click(object sender, EventArgs e)
        {
            int customerId = 0;
            string paymentMethod = "";
            string accountCode = "";
            string orderBy = ddlSort.SelectedValue.Equals("1") ? "Id desc" : "Id asc";
            string systemStatus = "";
            string orderTransactionStatus = "";
            string statusNotIn = "SystemStatus NOT IN ('ORDER_H','ORDER_D')";

            grvOrders.DataSource = new DataView(new cmsOrdersBL().SearchAdvance(customerId, paymentMethod, accountCode, orderBy, systemStatus, orderTransactionStatus, statusNotIn), statusNotIn, "", DataViewRowState.CurrentRows).ToTable();
            grvOrders.DataBind();
            UpdatePanel1.Update();
        }


        protected void btnFilter_Click(object sender, EventArgs e)
        {
            grvOrdersDataSource();
            UpdatePanel1.Update();
        }

        protected void grvOrders_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int UserID = int.Parse(Session["UserID"].ToString());
            string CommandName = e.CommandName;
            int orderId = int.Parse(e.CommandArgument.ToString());
            cmsOrdersDO objOrder = new cmsOrdersDO();
            cmsOrdersBL orderBL = new cmsOrdersBL();


            if (CommandName.ToLower().Equals("hideorder"))
            {
                try
                {
                    objOrder.Id = orderId;
                    objOrder = orderBL.Select(objOrder);
                    objOrder.SystemStatus = EnumStatus.V_ORDER_HIDDEN;
                    objOrder.TransactionOrderStatus = EnumTransactionOrderStatus.V_ORDER_COMPLETED;
                    objOrder.LastModifiedId = UserID;
                    objOrder.LastSaveDate = DateTime.Now;

                    orderBL.Update(objOrder);

                    CS_OrderHistoryDO objOrderHistory = new CS_OrderHistoryDO();
                    objOrderHistory.Action = EnumOrderHistory.V_CHANGE_HIDDEN;
                    objOrderHistory.Contents = EnumOrderHistory.V_CHANGE_HIDDEN_TEXT;
                    objOrderHistory.CreateDate = DateTime.Now;
                    objOrderHistory.OrderId = objOrder.Id;
                    objOrderHistory.UserId = UserID;
                    objOrderHistory.Note = "";
                    objOrderHistory.IP = Request.ServerVariables["REMOTE_ADDR"].Trim();

                    new CS_OrderHistoryBL().Insert(objOrderHistory);

                    //Functions.Alert("Cập nhật thành công!", "/Admincp/ListOrders.aspx");
                    ScriptManager.RegisterClientScriptBlock(this.Page, typeof(Page), "HideOrderScript", "<script type='text/javascript'>alert('Ẩn đơn hàng thành công!')</script>", false);
                    grvOrdersDataSource();

                    UpdatePanel1.Update();
                }
                catch
                {
                    ScriptManager.RegisterClientScriptBlock(this.Page, typeof(Page), "ErrorScript", "<script type='text/javascript'>alert('Có lỗi xảy ra!')</script>", false);

                    UpdatePanel1.Update();
                }
            }
            else if (CommandName.ToLower().Equals("deleteorder"))
            {
                try
                {
                    objOrder.Id = orderId;
                    objOrder = orderBL.Select(objOrder);
                    objOrder.SystemStatus = EnumStatus.V_ORDER_DELETE;
                    objOrder.TransactionOrderStatus = EnumTransactionOrderStatus.V_ORDER_COMPLETED;
                    objOrder.LastModifiedId = UserID;
                    objOrder.LastSaveDate = DateTime.Now;

                    orderBL.Update(objOrder);

                    CS_OrderHistoryDO objOrderHistory = new CS_OrderHistoryDO();
                    objOrderHistory.Action = EnumOrderHistory.V_CHANGE_DELETE;
                    objOrderHistory.Contents = EnumOrderHistory.V_CHANGE_DELETE_TEXT;
                    objOrderHistory.CreateDate = DateTime.Now;
                    objOrderHistory.OrderId = objOrder.Id;
                    objOrderHistory.UserId = UserID;
                    objOrderHistory.Note = "";
                    objOrderHistory.IP = Request.ServerVariables["REMOTE_ADDR"].Trim();

                    new CS_OrderHistoryBL().Insert(objOrderHistory);

                    ScriptManager.RegisterClientScriptBlock(this.Page, typeof(Page), "DeleteOrderScript", "<script type='text/javascript'>alert('Xóa đơn hàng thành công!')</script>", false);
                    grvOrdersDataSource();

                    UpdatePanel1.Update();
                }
                catch
                {
                    ScriptManager.RegisterClientScriptBlock(this.Page, typeof(Page), "ErrorScript", "<script type='text/javascript'>alert('Có lỗi xảy ra!')</script>", false);

                    UpdatePanel1.Update();
                }
            }
            else if (CommandName.ToLower().Equals("detail"))
            {
                try
                {
                    objOrder.Id = orderId;
                    objOrder = orderBL.Select(objOrder);
                    if (objOrder.TransactionOrderStatus.Equals(EnumTransactionOrderStatus.V_ORDER_NEW))
                    {
                        objOrder.TransactionOrderStatus = EnumTransactionOrderStatus.V_ORDER_PROCESSING;
                        objOrder.LastModifiedId = UserID;
                        objOrder.LastSaveDate = DateTime.Now;

                        orderBL.Update(objOrder);
                    }

                    CS_OrderHistoryDO objOrderHistory = new CS_OrderHistoryDO();
                    objOrderHistory.Action = EnumOrderHistory.V_VIEW;
                    objOrderHistory.Contents = EnumOrderHistory.V_VIEW_TEXT;
                    objOrderHistory.CreateDate = DateTime.Now;
                    objOrderHistory.OrderId = objOrder.Id;
                    objOrderHistory.UserId = UserID;
                    objOrderHistory.Note = "";
                    objOrderHistory.IP = Request.ServerVariables["REMOTE_ADDR"].Trim();

                    new CS_OrderHistoryBL().Insert(objOrderHistory);

                    Response.Redirect("/Admincp/Order.aspx?OrderId=" + orderId);
                }
                catch
                {
                    Response.Redirect("/Admincp/Order.aspx?OrderId=" + orderId);
                }
            }
            else if (CommandName.ToLower().Equals("finishorder"))
            {
                try
                {
                    objOrder.Id = orderId;
                    objOrder = orderBL.Select(objOrder);
                    objOrder.TransactionOrderStatus = EnumTransactionOrderStatus.V_ORDER_COMPLETED;
                    objOrder.LastModifiedId = UserID;
                    objOrder.LastSaveDate = DateTime.Now;
                    objOrder.DateOfFisnish = DateTime.Now;

                    orderBL.Update(objOrder);

                    CS_OrderHistoryDO objOrderHistory = new CS_OrderHistoryDO();
                    objOrderHistory.Action = EnumOrderHistory.V_CHANGE_COMPLETE;
                    objOrderHistory.Contents = EnumOrderHistory.V_CHANGE_COMPLETE_TEXT;
                    objOrderHistory.CreateDate = DateTime.Now;
                    objOrderHistory.OrderId = objOrder.Id;
                    objOrderHistory.UserId = UserID;
                    objOrderHistory.Note = "";
                    objOrderHistory.IP = Request.ServerVariables["REMOTE_ADDR"].Trim();

                    new CS_OrderHistoryBL().Insert(objOrderHistory);

                    // if (objOrder.IsUseVirtualAccount)
                    // {
                    cmsAccountReceiveMoneyBL accountReceivedMoneyBL = new cmsAccountReceiveMoneyBL();
                    cmsAccountReceiveMoneyDO objAccountReceivedMoney = accountReceivedMoneyBL.SelectByOrder(objOrder.InvoiceNumber);
                    if (objAccountReceivedMoney != null)
                    {
                        if (objAccountReceivedMoney.ID > 0)
                        {
                            objAccountReceivedMoney.Status = EnumReceivedMoneyStatus.V_RECEIVED_OK;
                            objAccountReceivedMoney.UserId = UserID;
                            accountReceivedMoneyBL.Update(objAccountReceivedMoney);
                        }
                    }
                    //  }
                    //Functions.Alert("Cập nhật thành công!", "/Admincp/ListOrders.aspx");
                    ScriptManager.RegisterClientScriptBlock(this.Page, typeof(Page), "FinishOrderScript", "<script type='text/javascript'>alert('Xử lý hoàn tất đơn hàng thành công!')</script>", false);
                    grvOrdersDataSource();

                    UpdatePanel1.Update();
                }
                catch
                {
                    ScriptManager.RegisterClientScriptBlock(this.Page, typeof(Page), "ErrorScript", "<script type='text/javascript'>alert('Có lỗi xảy ra!')</script>", false);

                    UpdatePanel1.Update();
                }
            }
            else if (CommandName.ToLower().Equals("cancelorder"))
            {
                try
                {
                    objOrder.Id = orderId;
                    objOrder = orderBL.Select(objOrder);
                    objOrder.TransactionOrderStatus = EnumTransactionOrderStatus.V_ORDER_CANCEL;
                    objOrder.LastModifiedId = UserID;
                    objOrder.LastSaveDate = DateTime.Now;

                    orderBL.Update(objOrder);

                    CS_OrderHistoryDO objOrderHistory = new CS_OrderHistoryDO();
                    objOrderHistory.Action = EnumOrderHistory.V_CHANGE_CANCEL;
                    objOrderHistory.Contents = EnumOrderHistory.V_CHANGE_CANCEL_TEXT;
                    objOrderHistory.CreateDate = DateTime.Now;
                    objOrderHistory.OrderId = objOrder.Id;
                    objOrderHistory.UserId = UserID;
                    objOrderHistory.Note = "";
                    objOrderHistory.IP = Request.ServerVariables["REMOTE_ADDR"].Trim();

                    new CS_OrderHistoryBL().Insert(objOrderHistory);

                    if (objOrder.IsUseVirtualAccount)
                    {
                        cmsAccountReceiveMoneyBL accountReceivedMoneyBL = new cmsAccountReceiveMoneyBL();
                        cmsAccountReceiveMoneyDO objAccountReceivedMoney = accountReceivedMoneyBL.SelectByOrder(objOrder.InvoiceNumber);
                        if (objAccountReceivedMoney != null)
                        {
                            if (objAccountReceivedMoney.ID > 0)
                            {
                                objAccountReceivedMoney.Status = EnumReceivedMoneyStatus.V_RECEIVED_CANCEL;
                                objAccountReceivedMoney.UserId = UserID;
                                accountReceivedMoneyBL.Update(objAccountReceivedMoney);
                            }
                        }

                        // Cap nhat lai tai khoan
                        cmsAccountDO objAccount = new cmsAccountDO();
                        cmsAccountBL accountBL = new cmsAccountBL();
                        cmsLogAccountDO objLogAccount = new cmsLogAccountDO();
                        cmsLogAccountBL logAccountBL = new cmsLogAccountBL();
                        accountBL.AccountInfoObject(objOrder.CustomerId);

                        if (objAccount != null)
                        {
                            if (objAccount.AccountId > 0)
                            {
                                objAccount.DepositBeforeTran = objAccount.Deposite;
                                objAccount.Deposite = objAccount.Deposite + objOrder.GrandTotal;
                                objAccount.LastSaveDate = DateTime.Now;
                                objAccount.LastModifiedId = UserID;
                                accountBL.Update(objAccount);

                                // Ghi log tai khoan
                                objLogAccount.AccountId = objAccount.AccountId;
                                objLogAccount.Content = "Hoàn tiền vào tài khoản khi hủy đơn hàng: " + objOrder.InvoiceNumber;
                                objLogAccount.CreatedById = UserID;
                                objLogAccount.CreatedDate = DateTime.Now;
                                objLogAccount.CurrentDeposite = objAccount.Deposite;
                                objLogAccount.DepositBeforeTran = objAccount.DepositBeforeTran;
                                objLogAccount.FromCustomerId = objOrder.CustomerId;
                                objLogAccount.OrderId = objOrder.Id;
                                objLogAccount.LogAccountPaymentCode = "CANCELORDER";
                                objLogAccount.LogAccountPayment = "Hoàn tiền khi hủy đơn hàng!";
                                objLogAccount.LogAccountType = "INCREASE";
                                logAccountBL.Insert(objLogAccount);
                            }
                        }
                    }
                    ScriptManager.RegisterClientScriptBlock(this.Page, typeof(Page), "CancelhOrderScript", "<script type='text/javascript'>alert('Hủy đơn hàng thành công!')</script>", false);
                    grvOrdersDataSource();

                    UpdatePanel1.Update();
                }
                catch
                {
                    ScriptManager.RegisterClientScriptBlock(this.Page, typeof(Page), "ErrorScript", "<script type='text/javascript'>alert('Có lỗi xảy ra!')</script>", false);

                    UpdatePanel1.Update();
                }
            }
        }

        protected void grvOrders_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvOrders.PageIndex = e.NewPageIndex;
            grvOrdersDataSource();
            UpdatePanel1.Update();
        }
    }
}